<template>
  <div
    v-if="!isDispose"
    :id="echartsComponents"
    style="width: 100%;height: 300px"
  />
</template>

<script>
import * as echarts from 'echarts'

import { markRaw } from 'vue'

export default {
  name: "EchartsComes",
  props: {
    // 接收父组件传递过来的信息
    option: {
      type: Object, // 此处可以为Array或者Object或者其它，根据需求来。
      default: null
    }
  },
  data() {
    return {
      myEcharts: null,
      isDispose: false
    };
  },
  computed: {
    echartsComponents() {
      const timestamp = new Date().getTime();
      return `echarts${timestamp}${Math.random() * 100000}`;
    }
  },
  watch: {
    option:{
        handler() {
          console.log('1111111111')
        this.refreshEcharts();
      },
      deep: true
    },

    chartDataOptions: {
      handler() {
        this.refreshEcharts();
      },
      deep: true
    }
  },
  mounted() {
    this.initEcharts();
    this.$nextTick(() => {
      this.refreshEcharts();
    });
  },
  beforeDestroy() {
    if (this.myEcharts) {
      this.myEcharts.clear();
      this.myEcharts.dispose();
      this.isDispose = true;
    }
  },
  methods: {
    initEcharts() {
      this.isDispose = false;
      const $echartsDOM = document.getElementById(this.echartsComponents);
      this.myEcharts =markRaw(echarts.init($echartsDOM)) ;
      this.refreshEcharts();
    },
    // 图表刷新
    refreshEcharts() {
      // 渲染数据
      const option = this.option;
      this.myEcharts.clear();
      this.myEcharts.setOption(option);
    }
  }
};
</script>
